<template>
  <view class="container" v-if="!takePhotoStatus">
    <image :src="images.icons.skinAiBg" mode="widthFix" class="bg-img" />
    <image :src="images.icons.rotationAiIcon" mode="aspectFit" class="rotation-icon" />
    <button class="photo-btn" @click="takePhoto">
      <image :src="images.icons.camera" mode="aspectFit" class="camera-icon" />
      拍照测肤
    </button>
  </view>
  <view class="result-container" v-else>
    <view class="tab-container">
      <scroll-view scroll-x class="tab-scroll-view" :scroll-left="scrollLeft">
        <view class="tab-list">
          <view v-for="(tab, index) in tabs" :key="index" class="tab-item" :class="{ active: currentTab === index }"
            @tap="handleTabChange(index)">
            {{ tab.name }}
            <view class="tab-line" v-if="currentTab === index"></view>
          </view>
        </view>
      </scroll-view>
    </view>

    <view class="component-container">
      <view class="component-wrapper">
        <!-- 肤质  -->
        <SkinType v-if="currentTab === 0" :base64="base64" :result="analysisResult.skin_type" />
        <!-- 肤色 -->
        <SkinColor v-if="currentTab === 1" :base64="base64" :result="analysisResult.skin_color" />
        <!-- 粗糙度 -->
        <SkinRoughness v-if="currentTab === 2" :base64="base64"
          :result="{ blackhead: analysisResult.blackhead, pores: pores }" />
        <!-- 色素沉着 -->
        <SkinPigmentation v-if="currentTab === 3" :base64="base64" :result="analysisResult.skin_spot" />
        <!-- 衰老性 -->
        <SkinAging v-if="currentTab === 4" :base64="base64" :result="analysisResult" />
        <!-- 眼部问题 -->
        <SkinEyeProblems v-if="currentTab === 5" :base64="base64" :result="analysisResult" />
      </view>
      <DetailCard />
    </view>
  </view>
</template>

<script setup lang="ts">
import { images } from '@/config/images';
import { ref } from 'vue';
import SkinType from './components/skin-type.vue';
import SkinColor from './components/skin-color.vue';
import SkinPigmentation from './components/skin-pigmentation.vue';
import SkinRoughness from './components/skin-roughness.vue';
import SkinAging from './components/skin-aging.vue';
import SkinEyeProblems from './components/skin-eye-problems.vue';
import DetailCard from './components/detail-card.vue';

const takePhotoStatus = ref(false);
const currentTab = ref(-1);
const scrollLeft = ref(0);
const analysisResult = ref<any>(null);
const base64 = ref('');
const pores = ref(false);

const tabs = [
  { name: '肤质' },
  { name: '肤色' },
  { name: '粗糙度' },
  { name: '色素沉着' },
  { name: '衰老性' },
  { name: '眼部问题' }
];

const handleTabChange = (index: number) => {
  currentTab.value = index;
  // 计算每个tab的宽度（包含padding）
  const tabWidth = 120; // 40rpx左padding + 40rpx右padding + 文字宽度
  // 计算屏幕宽度的一半
  const screenWidth = uni.getSystemInfoSync().windowWidth;
  const halfScreen = screenWidth / 2;
  // 计算目标滚动位置：使选中的tab居中
  scrollLeft.value = index * tabWidth - halfScreen + tabWidth / 2;
};

// 处理API错误信息
const handleApiError = (error: any) => {
  let errorMessage = '分析失败';

  // 处理HTTP状态码为413的特殊情况
  if (error.statusCode === 413) {
    errorMessage = '图片大小超过5MB限制，请重新拍摄';
    uni.showToast({
      title: errorMessage,
      icon: 'none',
      duration: 3000
    });
    return;
  }

  // 处理其他错误情况
  if (error.data?.error_message) {
    switch (error.data.error_message) {
      case 'IMAGE_ERROR_UNSUPPORTED_FORMAT':
        errorMessage = '图片格式不支持，请重新拍摄';
        break;
      case 'NO_FACE_FOUND':
        errorMessage = '未检测到人脸，请重新拍摄';
        break;
      case 'INVALID_IMAGE_FACE':
        errorMessage = '人脸无效，请重新拍摄';
        break;
      case 'INVALID_IMAGE_SIZE':
        errorMessage = '图片尺寸不符合要求，请重新拍摄';
        break;
      case 'INVALID_FACE_SIZE':
        errorMessage = '人脸尺寸过小，请靠近一点重新拍摄';
        break;
      case 'INVALID_IMAGE_URL':
        errorMessage = '图片地址无效';
        break;
      case 'IMAGE_FILE_TOO_LARGE':
        errorMessage = '图片文件太大，请重新拍摄';
        break;
      case 'IMAGE_DOWNLOAD_TIMEOUT':
        errorMessage = '图片下载超时，请重试';
        break;
      case 'AUTHENTICATION_ERROR':
        errorMessage = 'API密钥验证失败';
        break;
      case 'AUTHORIZATION_ERROR':
        errorMessage = 'API未授权';
        break;
      case 'CONCURRENCY_LIMIT_EXCEEDED':
        errorMessage = '请求过于频繁，请稍后再试';
        break;
      case 'MISSING_ARGUMENTS':
        errorMessage = '缺少必要参数';
        break;
      case 'BAD_ARGUMENTS':
        errorMessage = '参数格式错误';
        break;
      case 'INTERNAL_ERROR':
        errorMessage = '服务器内部错误，请稍后重试';
        break;
      default:
        if (error.data.error_message.includes('INVALID_FACE_QUALITY')) {
          errorMessage = '人脸质量不佳，请调整姿势或光线重新拍摄';
        }
    }
  }

  uni.showToast({
    title: errorMessage,
    icon: 'none',
    duration: 3000
  });
};

const takePhoto = () => {
  uni.showActionSheet({
    itemList: ['拍照', '从相册选择'],
    success: (res) => {
      uni.chooseImage({
        count: 1,
        sourceType: res.tapIndex === 0 ? ['camera'] : ['album'],
        sizeType: ['compressed'], // 使用压缩图片以避免超过大小限制
        success: async (res) => {
          const tempFilePath = res.tempFilePaths[0];
          console.log(111, tempFilePath)
          uni.showLoading({
            title: '分析中...',
            mask: true
          });

          try {
            // 将图片转为base64
            base64.value = await uni.getFileSystemManager().readFileSync(tempFilePath, 'base64');
            const token = uni.getStorageSync('token')
            uni.uploadFile({
              url: `${import.meta.env.VITE_BASE_URL}/skin/analysis/analyze`,
              filePath: tempFilePath,
              name: 'file',
              header: {
                'Authorization': 'Bearer ' + token
              },
              success: (response) => {
                const res = JSON.parse(response.data);
                if (res.error_message) {
                  handleApiError(res);
                  return;
                }
                console.log('皮肤分析结果:', res);
                currentTab.value = 0;
                const cnResult = JSON.parse(res.data.analysisResult)
                uni.setStorageSync('cnResult', cnResult)
                const valueResult = JSON.parse(res.data.result)
                analysisResult.value = valueResult;
                console.log('cnResult:', cnResult);
                console.log('valueResult:', valueResult);
                // 判断毛孔问题
                pores.value = analysisResult.value.pores_forehead?.value === 1 ||
                  analysisResult.value.pores_jaw?.value === 1 ||
                  analysisResult.value.pores_left_cheek?.value === 1 ||
                  analysisResult.value.pores_right_cheek?.value === 1;
                takePhotoStatus.value = true; // 显示结果页面
                uni.showToast({
                  title: '分析完成',
                  icon: 'success'
                });
              },
              fail: (err) => {
                handleApiError(err);
              },
              complete: () => {
                uni.hideLoading();
              }
            });
          } catch (err) {
            uni.hideLoading();
            uni.showToast({
              title: '图片处理失败，请重试',
              icon: 'none'
            });
            console.error(err);
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '选择失败，请重试',
            icon: 'none'
          });
          console.error(err);
        }
      });
    }
  });
};
</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  position: relative;
  z-index: 1;
  background: rgb(13, 21, 89);

  .bg-img {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
  }

  .rotation-icon {
    width: 131rpx;
    height: 134rpx;
    position: absolute;
    top: 339rpx;
    left: 254rpx;
    z-index: 3;
    animation: rotate 3s linear infinite;
  }

  @keyframes rotate {
    from {
      transform: rotate(0deg);
    }

    to {
      transform: rotate(360deg);
    }
  }

}

.photo-btn {
  width: 702rpx;
  height: 83rpx;
  background: linear-gradient(0deg, #4AFFFF, #12A3FF);
  box-shadow: -1rpx -1rpx 9rpx 0rpx #08103D;
  border-radius: 7rpx;
  padding: 0;
  margin: 0;
  font-weight: bold;
  font-size: 32rpx;
  color: #FFFFFF;
  position: absolute;
  bottom: 121rpx;
  left: 50%;
  transform: translateX(-50%);
  z-index: 3;
  display: flex;
  align-items: center;
  justify-content: center;

  .camera-icon {
    width: 38rpx;
    height: 32rpx;
    margin-right: 20rpx;
  }
}

.result-container {
  min-height: 100vh;
  background: #fff;
}

.tab-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background: #fff;
  border-bottom: 1rpx solid #f5f5f5;
}

.tab-scroll-view {
  width: 100%;
  white-space: nowrap;
  height: 88rpx;
}

.tab-list {
  display: inline-flex;
  padding: 0 20rpx;
  height: 100%;
}

.tab-item {
  position: relative;
  padding: 0 40rpx;
  font-size: 28rpx;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  transition: all 0.3s ease;

  &.active {
    color: #333;
    font-weight: bold;

    .tab-line {
      position: absolute;
      bottom: 0;
      left: 40rpx;
      right: 40rpx;
      height: 4rpx;
      background: linear-gradient(90deg, #4AFFFF, #12A3FF);
      border-radius: 2rpx;
      transition: all 0.5s ease;
      animation: fadeIn 0.5s ease;
    }
  }

  &:active {
    opacity: 0.7;
    transform: scale(0.98);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scaleX(0);
  }

  to {
    opacity: 1;
    transform: scaleX(1);
  }
}

.component-container {
  margin-top: 88rpx;
}

.component-wrapper {
  animation: slideIn 0.3s ease;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(20rpx);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>